package us.lithub.ui.activity;

import java.util.List;

import us.lithub.R;
import us.lithub.Util;
import us.lithub.data.Book;
import us.lithub.data.Friend;
import us.lithub.data.WebConnector;
import us.lithub.ui.RowBook;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

/**
 * The Class MyLibrary.
 */
public class MyLibrary extends Activity {

	/** The Constant TAG. (used for debugging) */
	private static final String TAG = MyLibrary.class.getSimpleName();
	
	/** The Constant REQUEST_PICK_FRIEND. */
	private static final int REQUEST_PICK_FRIEND = 1;

	/** The username. */
	String username;
	
	/** The password. */
	String password;

	/** The wc. */
	private WebConnector wc;
	
	/** The my user id. */
	private int myUserID;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		Log.d(TAG, "starting MyLibrary activity");
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_my_library);

		myUserID = Util.getMyUserID(this);
		username = Util.getUsername(this);
		password = Util.getPassword(this);

		wc = WebConnector.getInstance();
		loadData();
	}

	/**
	 * Load data to populate the list view.
	 */
	private void loadData() {
		new Thread() {

			@Override
			public void run() {
				final List<Book> books = wc.getBooksForSelf(username, password);
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						// Create the adapter and bind data to the list view
						BookAdapter adapter = new BookAdapter(MyLibrary.this, R.layout.row_book, books);
						ListView lv = (ListView) findViewById(R.id.lvListView);
						lv.setAdapter(adapter);
						lv.setOnItemClickListener(new OnItemClickListener() {

							@Override
							public void onItemClick(AdapterView<?> parent, View view, int position, long id) {


								if (books.get(position).getStatus() != 101) {
									String theirUsername = Util.getUsernameById(MyLibrary.this, books.get(position).getOwnerID());
									confirmReturn(theirUsername, books.get(position).getTitle());
								} else {
									Intent intent = new Intent(MyLibrary.this, Friends.class);
									intent.putExtra(Book.ISBN, books.get(position).getIsbn());
									intent.putExtra(Book.TITLE, books.get(position).getTitle());
									intent.putExtra(Book.AUTHOR_TEXT, books.get(position).getAuthor());
									intent.putExtra(Book.STATUS, books.get(position).getStatus());
									intent.putExtra(Util.MODE, Util.MODE_PICK_FRIEND);
									intent.putExtra(Util.DIRECTION, Util.DIRECTION_LEND);
									startActivityForResult(intent, REQUEST_PICK_FRIEND);	
								}
							}
						});	
					}
				});
			};
		}.start();
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		if (requestCode == REQUEST_PICK_FRIEND) {
			if (resultCode != Activity.RESULT_OK) {
				Toast.makeText(this, "Cancelled", Toast.LENGTH_SHORT).show();
				return;
			}

			String bookTitle = intent.getStringExtra(Book.TITLE);
			String username = intent.getStringExtra(Friend.NAME);
			
			if (intent.getIntExtra(Util.DIRECTION, 0) == Util.DIRECTION_LEND) {
				confirmLend(username, bookTitle);
			} else if (intent.getIntExtra(Util.DIRECTION, 0) == Util.DIRECTION_RETURN) {
				confirmReturn(username, bookTitle);
			}
		}
	}

	/**
	 * Confirm lend with the user.
	 *
	 * @param theirUsername the their username
	 * @param bookTitle the book title
	 */
	private void confirmLend(final String theirUsername, final String bookTitle) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("Are you sure you want to lend " + bookTitle + " to "+theirUsername+" ?");
		builder.setCancelable(false);
		builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				new Thread() {
					@Override
					public void run() {
						wc.lendBook(username, password, theirUsername, bookTitle);
						finish();
					}
				}.start();
				dialog.cancel();
			}
		});
		builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				dialog.cancel();
			}
		});
		AlertDialog alert = builder.create();
		alert.show();
	}
	
	/**
	 * Confirm return.
	 *
	 * @param theirUsername the their username
	 * @param bookTitle the book title
	 */
	private void confirmReturn(final String theirUsername, final String bookTitle) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("Are you sure you want to return " + bookTitle + " to "+theirUsername+" ?");
		builder.setCancelable(false);
		builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				new Thread() {
					@Override
					public void run() {
						wc.returnBook(username, password, theirUsername, bookTitle);
						finish();
					}
				}.start();
				dialog.cancel();
			}
		});
		builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				dialog.cancel();
			}
		});
		AlertDialog alert = builder.create();
		alert.show();
	}

	/**
	 * The Class BookAdapter displays the book information in as a list item.
	 */
	private class BookAdapter extends ArrayAdapter<Book> {

		/** The context. */
		private Context context;
		
		/** The books. */
		private List<Book> books;

		/**
		 * Instantiates a new book adapter.
		 *
		 * @param context the context
		 * @param textViewResourceId the text view resource id
		 * @param books the books
		 */
		public BookAdapter(Context context, int textViewResourceId, List<Book> books) {
			super(context, textViewResourceId, books);
			this.context = context;
			this.books = books;
		}

		/* (non-Javadoc)
		 * @see android.widget.ArrayAdapter#getView(int, android.view.View, android.view.ViewGroup)
		 */
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = convertView;

			if (v == null) {
				LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = vi.inflate(R.layout.row_book, null);
			}

			Book book = books.get(position);

			if (book != null) {
				String username = Util.getUsernameById(context, book.getUserID());
				String ownername = Util.getUsernameById(context, book.getOwnerID());

				((RowBook) v).setTitle(book.getTitle());
				((RowBook) v).setAuthor(book.getAuthor());
				((RowBook) v).setImage(book.getIsbn());
				((RowBook) v).setRequestString(book.getStatus(), book.getOwnerID(), username, ownername, myUserID);
			}
			return v;
		}	
	}
}
